import { makeAutoObservable } from 'mobx';
import * as dict from '@/services/dict';
import * as api from './api';

export default class RsOrderStore {
  _args = {
    search: {},
    pg: {
      page: 0,
      sort: ['crDate;desc'],
      size: 10,
    },
  };
  total = 0;
  _orderStatus = '5';
  _orderRefundStatus = '0';
  orders = [];
  initAccounts = []; // 已经处理的分账信息
  accounts = []; // 原后端返回的分账信息
  loading = false;
  currentRequestId = null;

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  /**
   * @func
   * @desc 使用设置的请求参数和分页配置请求列表数据
   *       分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   * @return {}
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined));
    const { search, pg } = toJS(this._args);
    if (this._orderStatus === '5') {
      search.orderStatus = '';
    }
    if (!pg.sort?.length) delete pg.sort;
    this.loading = true;

    const requestId = new Date().getTime(); // 生成新的唯一标识符
    this.currentRequestId = requestId;

    try {
      // eslint-disable-next-line no-nested-ternary
      const total = this._orderStatus === '4'
        ? yield api.getOrderTicketCount({ search })
        : (this.isView ? yield api.ordersSearchCount({ search }) : yield api.count({ search }));

      // eslint-disable-next-line no-nested-ternary
      const orders = this._orderStatus === '4'
        ? yield api.getOrderTicket({ search, pg })
        : (this.isView ? yield api.ordersSearch({ search, pg }) : yield api.search({ search, pg }));

      if (this.currentRequestId === requestId) { // 确保响应是当前的请求
        this.total = total;
        this.orders = orders;
      }
    } finally {
      if (this.currentRequestId === requestId) {
        this.loading = false;
      }
    }
  }

  * get(orderId) {
    return yield api.get(orderId);
  }

  * update(order) {
    yield api.update(order);
    this.query();
  }

  * orderSponsorRefund(id, order, args) {
    yield api.orderSponsorRefund(id, order, args);
    this.query();
  }

  * getLogs(order) {
    const { taskIds = [], id } = order;
    const search = {
      targetType: 'rsOrder',
      targetIds: [...taskIds, id],
    };
    return yield api.getLogs({ search });
  }

  * getIdRefund(id, order) {
    const data = yield api.getIdRefund(id, order);
    const promiseAry = data.map((p) => api.get(p?.orderInfo?.orderId)
      .then((r) => ({ ...p, order: r })));
    return Promise.all(promiseAry);
  }

  * getOrderRefundTicket(args) {
    const data = yield api.getOrderRefundTicket(args);
    return data;
  }

  * orderRefundUpdate(order) {
    yield api.orderRefundUpdate(order);
    this.query();
  }

  * orderCancelRefund(args) {
    const { applicationId, orderInfo } = args;
    yield api.orderCancelRefund({ applicationId, orderId: orderInfo.orderId });
    this.query();
  }

  * orderCommitRefund(args) {
    const { applicationId, orderInfo } = args;
    yield api.orderCommitRefund({ applicationId, orderId: orderInfo.orderId });
    this.query();
  }

  /**
   * 发起线下支付
   * @param {*} data
   */
  * orderCreateOffline(data) {
    yield api.orderCreateOffline(data);
    this.query();
  }

  * sync() {
    yield api.syncScOrder();
    this.query();
  }

  * getAccount(id) {
    try {
      return yield api.getAccount(id);
    } catch (error) {
      console.log(error);
    }
  }

  * getTicket(search, pg) {
    return yield api.getOrderTicket({ search, pg });
  }

  * getTicketRefunds(search) {
    return yield api.getTicketRefunds(search);
  }

  * getOrderDiscountInfo(args) {
    return yield api.getOrderDiscountInfo(args);
  }

  * orderCancel(args) {
    yield api.orderCancel(args);
    this.query();
  }

  * orderEnableShare(args) {
    yield api.orderEnableShare(args);
    this.query();
  }

  async getOrderPayee(args) {
    try {
      return await api.getOrderPayee(args);
    } catch (error) {
      console.log('🚀 _ file: CcOrderStore.js:320 _ CcOrderStore _ getOrderPayee _ error:', error);
      throw error;
    }
  }

  * getDictItem(dictId, itemId) {
    return yield dict.getDictItem(dictId, itemId);
  }

  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  ticIdx(i) {
    return 0 * 10 + i + 1;
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }

  get orderStatus() {
    return this._orderStatus;
  }

  set orderStatus(value) {
    this._orderStatus = value;
    this._args.pg.page = 0;
    this.query({ page: 0 });
  }

  get tableSort() {
    if (this._args.pg.sort?.length) {
      const [fn, dir] = this._args.pg.sort[0].split(';');
      return { [fn]: dir };
    }
    return undefined;
  }
}
